package com.career.syn.util;

import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.SignatureException;

/**
 * 
* @ClassName: HmacShaUtil
* @Description: HmacSha工具类
* @author georgeli
* @date 2018年1月25日 下午5:08:35
 */
@SuppressWarnings("restriction")
public class HmacShaUtil {

	public static String calculateRFC2104HMAC(String key, String data, String signatureMethod) throws SignatureException {
		String result;
		try {
			SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), signatureMethod);
			Mac mac = Mac.getInstance(signatureMethod);
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data.getBytes());
			BASE64Encoder b64Encoder = new BASE64Encoder();
			result = b64Encoder.encode(rawHmac);
		} catch (Exception e) {
			throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
		}

		return result;
	}

}
